package com.example.urmsadmin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.urmsadmin.Util.CheckToken;
import com.example.urmsadmin.Util.PermissionService;
import com.example.urmsadmin.Util.SaltEncryption;
import com.example.urmsadmin.Util.ValidatorUtil;
import com.example.urmsadmin.entity.SysMenu;
import com.example.urmsadmin.entity.SysUser;
import com.example.urmsadmin.mapper.MenuMapper;
import com.example.urmsadmin.service.SysMenuService;
import com.example.urmsadmin.service.SysRoleMenuService;
import com.example.urmsadmin.service.SysUserService;
import com.example.urmsadmin.service.impl.SysMenuServiceImpl;
import com.example.urmsadmin.service.impl.SysRoleMenuServiceImpl;
import com.example.urmsadmin.service.impl.SysUserServiceImpl;
import com.example.urmsadmin.vo.CommonResult;
import com.example.urmsadmin.vo.TokenVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 菜单表(SysMenu)表控制层
 *
 * @author makejava
 * @since 2022-07-12 08:43:51
 */
@RestController
@Slf4j
@RequestMapping(value = "/sysMenu")
public class SysMenuController {
    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysMenuService menuService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private SysRoleMenuService roleMenuService;

    @GetMapping("/getMenu")
    public CommonResult<Object> getMenu(HttpServletRequest request)
    {
        log.info("执行了===>SysMenuController中的getMenu方法");
        //工具类验证token是否有效 有效返回tokenVo对象,否则返回null
        TokenVo tokenVo = new CheckToken().checkToken(request, userService);
        //有效token
        if (tokenVo != null) {
            List<SysMenu> menuList = null;
            if(tokenVo.getUserId().equals("1")){
                QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
                wrapper.select("DISTINCT *").orderByAsc("parent_id", "order_num");
                wrapper.eq("status","0");
                menuList =menuService.list(wrapper);
            }else{
                SysMenu sysMenu = new SysMenu();
                sysMenu.getParams().put("userId",tokenVo.getUserId());
                menuList = menuMapper.selectMenuListByUserId(sysMenu);
            }
            Map<Object, Object> result = new HashMap<>();
            result.put("menuList", menuList);
            return new CommonResult<>(200, "success", result);
        } else {
            return new CommonResult<>(233, "认证信息有误,获取数据失败");
        }

    }

    /**
     * @param menuName  菜单名
     * @param status    账号状态
     * @param menuType  菜单类型
     * @return
     */
    @PreAuthorize("@per.hasPermi('system:menu:query')")
    @GetMapping("/getMenuByQuInfo")
    public CommonResult<Object> getMenuByQuInfo(@RequestParam(required = false) String menuName,
                                        @RequestParam(required = false) String status,
                                        @RequestParam(required = false) String menuType) {
        log.info("执行了===>SysMenuController中的getMenuByQuInfo方法");
        //参数一是当前页，参数二是每页个数
        //查询条件(可选)
        QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
        if (!Objects.equals(menuName, "") && menuName != null) {
            wrapper.like("menu_name", menuName);
        }
        if (!Objects.equals(menuType, "") && menuType != null) {
            wrapper.like("menu_type", menuType);
        }
        if (!Objects.equals(status, "") && status != null) {
            wrapper.like("status", status);
        }
        wrapper.orderByAsc("parent_id", "order_num");
        List<SysMenu> menus = menuService.list(wrapper);
        // 创建分页结果集
        Map<Object, Object> result = new HashMap<>();
        result.put("menus", menus);
        return new CommonResult<>(200, "success", result);
    }

    /**
     * @param type    操作类型
     * @param menuIds 操作用户的id的字符串,以逗号分隔
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @GetMapping("/handleMenu/{type}")
    public CommonResult<String> handleMenu(@PathVariable("type") Integer type, String menuIds) {
        log.info("执行了===>SysUserController中的handleUser方法");
        //转换成数组 需要操作的用户的id数组
        String[] ids = menuIds.split(",");
        if (type == 1) {//启用
            if(!permissionService.hasPermi("system:menu:statusOn")){
                return new CommonResult<>(233, "无操作权限");
            }
            for (String id : ids) {
                //当前需要修改的用户
                SysMenu menu = menuService.getById(Integer.parseInt(id));
                menu.setStatus("0");//设置为有效的用户
                menuService.update(menu, new UpdateWrapper<SysMenu>().eq("menu_id", Integer.parseInt(id)));
            }
            return new CommonResult<>(200, "操作成功");
        } else if (type == 2) {//禁用
            if(!permissionService.hasPermi("system:menu:statusOff")){
                return new CommonResult<>(233, "无操作权限");
            }
            for (String id : ids) {
                //当前需要修改的用户
                SysMenu menu = menuService.getById(Integer.parseInt(id));
                menu.setStatus("1");//设置为无效的用户
                menuService.update(menu, new UpdateWrapper<SysMenu>().eq("menu_id", Integer.parseInt(id)));
            }
            return new CommonResult<>(200, "操作成功");
        } else if (type == 3) {//删除
            if(!permissionService.hasPermi("system:menu:remove")){
                return new CommonResult<>(233, "无操作权限");
            }
            for (String id : ids) {
                menuService.removeById(Long.parseLong(id));
                QueryWrapper wrapper = new QueryWrapper();
                wrapper.eq("menu_id",id);
                roleMenuService.remove(wrapper);
            }
            return new CommonResult<>(200, "操作成功");
        } else {
            return new CommonResult<>(233, "操作有误");
        }
    }

    /**
     * @param menu 菜单实体
     * @return
     */
    @PreAuthorize("@per.hasPermi('system:menu:add')")
    @PostMapping("/addMenu")
    public CommonResult<String> addMenu(@RequestBody SysMenu menu){
        log.info("执行了===>SysMenuController中的addMenu方法");
        if(ValidatorUtil.isMenuName(menu.getMenuName())&&ValidatorUtil.isRemark(menu.getRemark())){
        }else{
            return new CommonResult<>(233,"数据不合法");
        }
        menu.setCreateTime(new Date());
        boolean save = menuService.save(menu);
        return  new CommonResult<>(200, "操作成功") ;
    }

    /**
     * @param menu 菜单实体
     * @return
     */
    @PreAuthorize("@per.hasPermi('system:menu:edit')")
    @PostMapping("/updateMenu")
    public CommonResult<String> updateMenu(@RequestBody SysMenu menu){
        log.info("执行了===>SysMenuController中的updateMenu方法");
        if(ValidatorUtil.isMenuName(menu.getMenuName())&&ValidatorUtil.isRemark(menu.getRemark())){
        }else{
            return new CommonResult<>(233,"数据不合法");
        }
        QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
        wrapper = new QueryWrapper<SysMenu>().eq("menu_id", menu.getMenuId());
        // 查询当前用户信息
        SysMenu menuData = menuService.getOne(wrapper);

        if (menuData != null) {
            menuData.setUpdateTime(new Date());
            menuData.setMenuName(menu.getMenuName());
            menuData.setParentId(menu.getParentId());
            menuData.setOrderNum(menu.getOrderNum());
            menuData.setMenuUrl(menu.getMenuUrl());
            menuData.setComponent(menu.getComponent());
            menuData.setMenuPerms(menu.getMenuPerms());
            menuData.setStatus(menu.getStatus());
            menuData.setIcon(menu.getIcon());
            menuData.setRemark(menu.getRemark());

            boolean update = menuService.update(menuData, wrapper);
            return update ? new CommonResult<>(200, "更新菜单信息成功") :
                    new CommonResult<>(233, "更新菜单信息失败");
        }else {
            throw new RuntimeException("获取菜单信息失败！");
        }
    }

    /**
     * 获取用户权限信息
     *
     * @return 用户权限信息
     */
    @GetMapping("/getPermissions")
    public CommonResult<Object> getPermissions(HttpServletRequest request)
    {
        log.info("执行了===>SysMenuController中的getPermissions方法");
        //工具类验证token是否有效 有效返回tokenVo对象,否则返回null
        TokenVo tokenVo = new CheckToken().checkToken(request, userService);
        //有效token
        if (tokenVo != null) {
            // 权限集合
            Set<String> permissions = menuService.getMenuPermission(Long.parseLong(tokenVo.getUserId()));
            return new CommonResult<>(200, "success", permissions);
        } else {
            return new CommonResult<>(233, "认证信息有误,获取数据失败");
        }
    }
}

